﻿using System;
using System.Linq;
using Microsoft.SharePoint.Administration;

namespace Xodeuz.SP.Common
{
    public class Logger
    {
        /// <summary>
        /// Find Diagnostics Category by name
        /// </summary>
        public static SPDiagnosticsCategory FindCategory(String name)
        {
            return SPDiagnosticsService.Local.Areas.Select(area => area.Categories.FirstOrDefault(cat => cat.Name == name)).FirstOrDefault(category => category != null);
        }

        /// <summary>
        /// Find Diagnostics Area by name
        /// </summary>
        public static SPDiagnosticsArea FindArea(String areaName)
        {
            return SPDiagnosticsService.Local.Areas[areaName];
        }

        /// <summary>
        /// Log Error to ULS
        /// </summary>
        protected static void LogError(String category, Exception ex)
        {
            LogError(new SPDiagnosticsCategory(category, TraceSeverity.Unexpected, EventSeverity.Error), ex);
        }

        /// <summary>
        /// Log Error to EventLog
        /// </summary>
        protected static void LogEvent(String category, Exception ex)
        {
            LogEvent(new SPDiagnosticsCategory(category, TraceSeverity.Unexpected, EventSeverity.Error), ex);
        }

        /// <summary>
        /// Log Error to ULS
        /// </summary>
        protected static void LogError(SPDiagnosticsCategory category, Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, category, TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }

        /// <summary>
        /// Log Error to EventLog
        /// </summary>
        protected static void LogEvent(SPDiagnosticsCategory category, Exception ex)
        {
            SPDiagnosticsService.Local.WriteEvent(0, category, EventSeverity.Error, ex.Message, ex.StackTrace);
        }
    }
}
